<script setup lang="ts">
import {computed, onMounted, reactive, ref} from 'vue'
import {UploadFilled} from '@element-plus/icons-vue'
import type {FormInstance, FormRules} from 'element-plus'
import {ElNotification} from 'element-plus'
import {get, post} from '../utils/axios-request.js'
import router from "../router.js";

/**
 * Form校验
 */
interface RuleForm {
  imageKey: string,
  author: string,
  name: string,
  length: string,
  width: string,
  height: string,
  material: string,
  editions: number,
  year: number,
  price: number,
  type: number,
  sellStatus: string,
  sizeVariable: boolean,
  remarks: string,
}

const ruleFormRef = ref<FormInstance>();

const form = reactive<RuleForm>({
  imageKey: '',
  author: '',
  name: '',
  length: null,
  width: null,
  height: null,
  material: '',
  editions: null,
  year: null,
  price: null,
  type: null,
  sellStatus: '0',
  sizeVariable: false,
  remarks: ''
})

const rules = reactive<FormRules<RuleForm>>({
  imageKey: [
    {required: true, message: '请上传藏品/作品图', trigger: 'blur'}
  ],
  author: [
    {required: true, message: '请填写艺术家', trigger: 'blur'}
  ],
  name: [
    {required: true, message: '请填写作品名称', trigger: 'blur'}
  ],
  material: [
    {required: true, message: '请填写材质', trigger: 'blur'}
  ],
  price: [
    {required: true, message: '请填写价格', trigger: 'blur'}
  ],
  year: [
    {
      required: true,
      message: '请选择年份',
      trigger: 'change',
    }
  ],
  type: [
    {
      required: true,
      message: '请选择类型',
      trigger: 'change',
    }
  ]
})

/**
 * form提交
 */
const submitLoading = ref(false);

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  submitLoading.value = true;
  await formEl.validate((valid, fields) => {
    if (valid) {
      post('/pdf/upload/artwork', form, () => {
        ElNotification({
          title: 'Success',
          message: '作品上传成功！',
          type: 'success',
          duration: 1000,
          onClose: () => {
            router.push('/artwork/list')
          }
        })
      }, (message) => {
        ElNotification({
          title: 'Error',
          message: message,
          duration: 1500,
          type: 'error'
        })
        submitLoading.value = false;
      });

    } else {
      submitLoading.value = false;
      console.log('error submit!', fields)
    }
  })
}

/**
 * 年份下拉
 */
// 计算当前年份
const currentYear = ref(new Date().getFullYear());

// 计算年份范围（1976 到当前年份）
const years = computed(() => {
  return Array.from(
      {length: currentYear.value - 1976 + 1}, // 计算年份数量
      (_, i) => currentYear.value - i // 生成 1976, 1977, ..., 当前年份
  );
});

/**
 * 上传图片
 * @param response
 */

const beforeUpload = file => {
  const maxSize = 5 * 1024 * 1024; // 5MB
  if (file.size > maxSize) {
    ElNotification({
      title: 'Error',
      message: '上传文件不能超过5MB',
      type: 'error',
    })
    return false; // 阻止上传
  }
  return true; // 允许上传
}

const uploadImageSuccess = (response) => {
  if (response && response.status === '0000') {
    form.imageKey = response.data;
  } else if (response && response.status === '401') {
    ElNotification({
      title: 'Error',
      message: response.message,
      type: 'error',
      duration: 1000,
      onClose: () => {
        router.push('/login');
      }
    })
  }
};

const viteApiHost = ref(import.meta.env.VITE_API_HOST);

const uploadUrl = computed(() => viteApiHost.value + '/pdf/upload/image');

const deleteImage = () => {

  if (form.imageKey) {
    get('/pdf/delete/image?imageKey=' + form.imageKey)
  }
}
/**
 * 尺寸label显示
 */

const lengthPlaceholder = ref('长（cm）');
const widthPlaceholder = ref('宽（cm）');
const heightPlaceholder = ref('高（cm）');

const typeOnchange = (value) => {
  if (value === 6) {
    lengthPlaceholder.value = '时';
    widthPlaceholder.value = '分';
    heightPlaceholder.value = '秒';
  } else if (value === 7 || value === 4) {
    lengthPlaceholder.value = '高（cm）';
    widthPlaceholder.value = '宽（cm）';
    heightPlaceholder.value = '深（cm）';
  } else {
    lengthPlaceholder.value = '长（cm）';
    widthPlaceholder.value = '宽（cm）';
    heightPlaceholder.value = '高（cm）';
  }
}

/**
 * 获取类型下拉
 */
const types = ref([]);

onMounted(() => {
  get('/public/data/selectors/ARTWORK_TYPE', (list) => {
    types.value = list;
  })
});

</script>
<template>
  <div class="form-container">
    <el-form ref="ruleFormRef" :model="form" label-width="auto" style="width: 60% " :rules="rules">
      <el-form-item label="藏品/作品图" prop="imageKey" required>
        <el-upload
            class="upload-image"
            drag
            :limit="1"
            list-type="picture"
            :action="uploadUrl"
            :on-success="uploadImageSuccess"
            accept=".jpg,.jpeg,.png"
            :before-upload="beforeUpload"
            :on-remove="deleteImage"
        >
          <el-icon class="el-icon--upload">
            <upload-filled/>
          </el-icon>
          <div class="el-upload__text">
            拖拽作品到这或者 <em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              jpg/png/jpeg 格式的图片，最大不超过5MB
            </div>
          </template>
        </el-upload>
        <el-input type="hidden" v-model="form.imageKey"/>
      </el-form-item>
      <el-form-item label="艺术家姓名" required prop="author">
        <el-input v-model="form.author" placeholder="请输入艺术家姓名，请去掉多余空格"/>
      </el-form-item>
      <el-form-item label="作品名称" required prop="name">
        <el-input v-model="form.name" placeholder="请输入作品名称"/>
      </el-form-item>
      <el-form-item label="备注/说明">
        <el-input
            v-model="form.remarks"
            :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea"
            maxlength="200"
            show-word-limit
            placeholder="对作品进行补充和说明"
        />
      </el-form-item>
      <el-form-item label="尺寸">
        <el-switch
            v-model="form.sizeVariable"
            class="ml-2"
            inline-prompt
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
            active-text="可变"
            inactive-text="不可变"
            width="80"
        />
      </el-form-item>
      <el-form-item v-if="!form.sizeVariable" label="尺寸详情">
        <el-col :span="6">
          <el-form-item prop="length">
            <el-input v-model="form.length" type="number" class="artwork-size"
                      :placeholder="lengthPlaceholder"/>
          </el-form-item>
        </el-col>
        ×
        <el-col :span="6">
          <el-form-item prop="width">
            <el-input v-model="form.width" type="number" class="artwork-size margin-left"
                      :placeholder="widthPlaceholder"/>
          </el-form-item>
        </el-col>
        ×
        <el-col :span="6">
          <el-form-item prop="height">
            <el-input v-model="form.height" type="number" class="artwork-size margin-left"
                      :placeholder="heightPlaceholder"/>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="材质" required prop="material">
        <el-input v-model="form.material" placeholder="国画、油画、版画、雕塑等等"/>
      </el-form-item>
      <el-form-item label="版数" v-if="[3, 4, 6].includes(form.type)">
        <el-input v-model="form.editions" type="number" placeholder="限于版画、雕塑、影像使用"/>
      </el-form-item>
      <el-form-item label="年份" required prop="year">
        <el-select v-model="form.year" placeholder="请选择年份">
          <el-option v-for="year in years" type="number" :label="year" :value="year"/>
        </el-select>
      </el-form-item>
      <el-form-item label="价格" required prop="price">
        <el-input v-model="form.price" type="number" placeholder="单位：元"/>
      </el-form-item>
      <el-form-item label="售卖状态" required prop="sellStatus">
        <el-radio-group v-model="form.sellStatus">
          <el-radio :value="true">已售</el-radio>
          <el-radio :value="false">未售</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="类型" required prop="type">
        <el-select v-model="form.type" placeholder="请选择类型" @change="typeOnchange">
          <el-option v-for="option in types" :label="option.label" :value="option.value"/>
        </el-select>
      </el-form-item>
      <div class="button-div">
        <el-button class="large-button"
                   :loading="submitLoading"
                   plain
                   size="large"
                   type="primary"

                   @click="submitForm(ruleFormRef)">
          确认上传
        </el-button>
      </div>
    </el-form>
  </div>
</template>
<style scoped>

.upload-image {
  width: 100%;
}

.artwork-size {
  margin-right: 10px;
}

.margin-left {
  margin-left: 10px;
}

.large-button {
  width: 80%;
}

.button-div {
  /* 使用 Flexbox 让按钮居中 */
  display: flex;
  justify-content: center; /* 水平居中 */
  gap: 10px; /* 按钮之间的间距 */
}
</style>
